# -*- coding: utf-8 -*-
import webapp2
import exceptions

from lkshonok import Lkshonok
from webapp2 import uri_for


class View(webapp2.RequestHandler):

    def get(self, *args, **kwargs):
        exc = ['Hell', 'Zoo', 'Intel', 'Hutor']
        couexcur = len(exc)
        peoples = Lkshonok.query()
        lkshata = []
        for i in peoples:
            if i.fam != '' and i.nam != '':
                lkshata.append(i)
        self.response.write('<html><body>Excursions : <ul>')
        excursions =[]
        for i in range(couexcur):
            b = []
            excursions.append(b)
        for i in range(len(lkshata)):
            for j in range(len(lkshata) - 1):
                if (lkshata[j].fam > lkshata[j + 1].fam) or (lkshata[j].fam == lkshata[j + 1].fam and lkshata[j].nam > lkshata[j + 1].nam):
                    lkshata[j + 1], lkshata[j] = lkshata[j], lkshata[j + 1]
        for lksh in lkshata:
            excursions[lksh.ind - 1].append(lksh)
        for i in range(len(excursions)):
            s = str(exc[i]) + ' ' + str(len(excursions[i]))
            self.response.write('<li>%s</li>' % (s))
            for j in range(len(excursions[i])):
                if excursions[i][j].fam != '' and excursions[i][j].nam != '':
                    s = str(j + 1) + ')' + excursions[i][j].fam + ' ' + excursions[i][j].nam
                    self.response.write('<li>%s</li>' % (s))
        self.response.write("""</ul>
           <form action="%s" method="POST">

                <input type="radio" name="variant" value="1">Hell<br>
                <input type="radio" name="variant" value="2">Zoo<br>
                <input type="radio" name="variant" value="3">Intel<br>
                <input type="radio" name="variant" value="4">Hutor<br>
                <label for="fam">Фамилия</label>
                <input type="text" size="65" name="fam" value=""><br>
                <label for="nam">Имя    </label>
                <input type="text" size="70" name="nam" value=""><br>
                <input type="submit" value="Add">

            </form>
        </html>""" % (uri_for('add')))


class Add(webapp2.RequestHandler):
    def __init__(self, *args, **kwargs):
        super(Add, self).__init__(*args, **kwargs)

    def post(self, *args, **kwargs):
        try:
            fam = self.request.get('fam')
            nam = self.request.get('nam')
            valexc = int(self.request.get('variant'))
        except exceptions.ValueError:
            self.redirect(uri_for('show'))
            return
        if fam == '' or nam == '':
            return
        new_lkshonok = Lkshonok(fam = fam, nam = nam, ind = valexc)
        new_lkshonok.put()
        self.redirect(uri_for('show'))

